package controller;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Controller
public class RegistUserServlet extends HttpServlet {
    @Autowired
    private  UserService service;

    @RequestMapping(value = "/registUserServlet")
    public String register(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {

        //1.获取数据
        Map<String, String[]> map = request.getParameterMap();

        //封装对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
            System.out.println(user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        User u = service.regist(user);

        if(u != null){
            session.setAttribute("user",u);
            return "redirect:/register_ok.jsp";
        }
        request.setAttribute("msg", "用户名已存在！");
        request.getRequestDispatcher("/register.jsp").forward(request, response);
        return "redirect:/register.jsp";
    }
}
